#include "downloadwindow.h"
#include "ui_downloadwindow.h"

DownloadWindow::DownloadWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::DownloadWindow)
{
    ui->setupUi(this);
    resize(600, 300);
    setWindowTitle(tr("下载管理器"));
    setWindowIcon(QIcon(QStringLiteral(":/app_resource/logo.png")));
}

DownloadWindow::~DownloadWindow()
{
    delete ui;
}

void DownloadWindow::add(DownloadWidget *download)
{

    connect(download, &DownloadWidget::removeClicked, this, &DownloadWindow::remove);
    this->ui->m_itemsLayout->insertWidget(0, download, 0, Qt::AlignTop);
    if (m_numDownloads++ == 0)
        this->ui->m_zeroItemsLabel->hide();
}

void DownloadWindow::remove(DownloadWidget *download)
{
    this->ui->m_itemsLayout->removeWidget(download);
    download->deleteLater();
    if (--m_numDownloads == 0)
        this->ui->m_zeroItemsLabel->show();
}

void DownloadWindow::downloadRequest(QWebEngineDownloadRequest *download)
{
    // TODO，处理下载（文件下载需要进行安全检验）
    qDebug() << "处理文件下载";
    Q_ASSERT(download && download->state() == QWebEngineDownloadRequest::DownloadRequested);
    qDebug() << "download path: " << ConfigManager::getInstance().getDownloadPath();
    download->setDownloadDirectory(ConfigManager::getInstance().getDownloadPath());
    QString path = QFileDialog::getSaveFileName(this, tr("文件下载"), download->downloadDirectory() + "//" + download->downloadFileName());
    if (path.isEmpty())
        return;
    download->setDownloadFileName(path);
    download->accept();
    add(new DownloadWidget(download, this));
    show();
    int res = FileCheckManager::instance()->check(path);
    if(!res){
        NotifyManager *manager = new NotifyManager();
        manager->setMaxCount(5);
        manager->setDisplayTime(5000);
        manager->setNotifyWndSize(500, 200);
        manager->notify("警告", "下载的文件可能是一个已知的不安全文件，建议删除该文件");
//        QMessageBox msgBox;
//        msgBox.setText("The file maybe has been modified and it is not safe!!");
//        msgBox.exec();
    }
}
